package com.kaiwukj.android.ufamily.mvp.ui.widget;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SizeUtils;

/**
 * Created by Administrator on 2019/10/25
 */
public class GridSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private int lrSpace, tbSpace;

    public GridSpaceItemDecoration(int lrSpace, int tbSpace) {
        this.lrSpace = SizeUtils.dp2px(lrSpace);
        this.tbSpace = SizeUtils.dp2px(tbSpace);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect,
                               @NonNull View view,
                               @NonNull RecyclerView parent,
                               @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (parent.getLayoutManager() instanceof GridLayoutManager) {
            GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
            if (layoutManager != null) {
                int spanCount = layoutManager.getSpanCount();
                int pos = parent.getChildAdapterPosition(view);
                int spanIndex = layoutManager.getSpanSizeLookup().getSpanIndex(pos, spanCount);
                //int spanSize = layoutManager.getSpanSizeLookup().getSpanSize(pos);
                int childCount = layoutManager.getItemCount();
                int rows = childCount / spanCount;//总行
                if (childCount % spanCount > 0) {
                    rows += 1;
                }
                int posRows = (pos + 1) / spanCount;
                if ((pos + 1) % spanCount > 0) {
                    posRows += 1;
                }

                if (spanIndex == 0) {//第一列
                    outRect.right = lrSpace / 2;
                } else if (spanIndex == spanCount - 1) {//最后一列
                    outRect.left = lrSpace / 2;
                } else {
                    outRect.left = lrSpace / 2;
                    outRect.right = lrSpace / 2;
                }

               /* if (pos <= spanCount - 1) {//第一排
                    //outRect.bottom = tbSpace / 2;
                } else if (posRows == rows) {//最后一排
                    outRect.top = tbSpace;
                } else {
                    outRect.top = tbSpace / 2;
                    outRect.bottom = tbSpace / 2;
                }*/
                if (pos > spanCount - 1) {//不是第一行
                    outRect.top = tbSpace;
                }
            }
        }
    }

}
